package com.jsy.learnnetty.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author: SongyangJi
 * @description:
 * @since: 2021/10/13
 */
public class ServerEnd {

    int port;

    public ServerEnd(int port) {
        this.port = port;
        start();
    }


    public void start() {

        EchoServerHandler echoServerHandler = new EchoServerHandler();
        EventLoopGroup eventExecutors = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
                .group(eventExecutors)
                .channel(NioServerSocketChannel.class)
                .localAddress(port)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(echoServerHandler);
                    }
                });

        try {
            ChannelFuture future = serverBootstrap.bind().sync();
            System.out.println("listen ...");
            future.channel().closeFuture().sync();
            System.out.println("server channel close...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                eventExecutors.shutdownGracefully().sync();
                System.out.println("server end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        new ServerEnd(7777);
    }
}
